<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 账户表
// +----------------------------------------------------------------------
namespace app\sso\model;

use Inphp\Core\Db\PDO\Model;
use Inphp\Core\Modules;

class ThirdPartyAppModel extends Model
{
    /**
     * 表名
     * @var string
     */
    protected string $tableName = "sso_thirdPartyApp";

    /**
     * 主键字段
     * @var string
     */
    protected string $primaryKey = "id";

    /**
     * 获取列表
     * @param string|null $plugin
     * @return array
     */
    public static function getList(?string $plugin = null): array
    {
        $list = Modules::getModule("sso")->getConfig("thirdPartyApp");
        $list = is_array($list) ? $list : [];
        if (empty($plugin)) {
            return $list;
        }
        $res = [];
        foreach ($list as $item) {
            if ($item["plugin"] == $plugin) {
                $res[] = $item;
            }
        }
        return $res;
    }

    /**
     * 缓存
     * @return bool
     */
    public static function cache(): bool
    {
        $appList = ThirdPartyAppModel::emptyQuery()->get();
        $appConfig = [];
        foreach ($appList as $app) {
            $appConfig[] = [
                "appid"     => $app["appid"],
                "secret"    => $app["secret"],
                "plugin"    => $app["plugin"],
                "state"     => $app["state"] == 1,
                "param"     => $app["param"]
            ];
        }
        //保存到缓存
        $module = Modules::getModule("sso");
        $config = $module->getConfig();
        $config["thirdPartyApp"] = $appConfig;
        return Modules::getModule("sso")->saveConfig("config", $config);
    }
}